<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { IPsychologicalUser } from '@/api/type';
import { fetchUserList, updateUser, deleteUser } from '@/api/user';
import { useSnackbarStore } from '@/store/snackbarStore';

const itemsPerPage = ref(10);
const showFilter = ref(true);
const users = ref<IPsychologicalUser[]>([]);
const loading = ref(true);
const snackbarStore = useSnackbarStore();

// 编辑对话框相关
const editDialog = ref(false);
const editingUser = ref<IPsychologicalUser | null>(null);
const editForm = reactive({
  username: '',
  name: '',
  phone: '',
  gender: '',
  role: '',
  is_active: true
});

// 删除确认对话框
const deleteDialog = ref(false);
const deletingUser = ref<IPsychologicalUser | null>(null);

const filters = reactive({
  role: '',
  gender: '',
  is_active: null as boolean | null
});

// 角色选项
const roleOptions = [
  { title: '学生', value: 'STUDENT' },
  { title: '初访员', value: 'INITIAL_VISITOR' },
  { title: '心理助理', value: 'ASSISTANT' },
  { title: '咨询师', value: 'CONSULTANT' },
  { title: '管理员', value: 'ADMIN' }
];

// 性别选项
const genderOptions = [
  { title: '男', value: 'M' },
  { title: '女', value: 'F' }
];

// 状态选项
const statusOptions = [
  { title: '激活', value: true },
  { title: '禁用', value: false }
];

// 表格列定义（去掉创建时间列）
const headers = reactive([
  { title: 'ID', key: 'id', width: '80px' },
  { title: '学号', key: 'username' },
  { title: '姓名', key: 'name' },
  { title: '角色', key: 'role' },
  { title: '性别', key: 'gender' },
  { title: '电话', key: 'phone' },
  { title: '状态', key: 'is_active' },
  { title: '操作', key: 'action', sortable: false, width: '150px' }
]);

// 获取角色显示文本
const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    'STUDENT': '学生',
    'INITIAL_VISITOR': '初访员',
    'ASSISTANT': '心理助理',
    'CONSULTANT': '咨询师',
    'ADMIN': '管理员'
  };
  return roleMap[role] || role;
};

// 获取性别显示文本
const getGenderText = (gender: string) => {
  return gender === 'M' ? '男' : '女';
};

// 获取状态颜色
const getStatusColor = (isActive: boolean) => {
  return isActive ? 'success' : 'error';
};

// 解析额外信息
const parseExtraInfo = (extraInfo: string) => {
  try {
    return JSON.parse(extraInfo);
  } catch {
    return {};
  }
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    console.log('Loading psychological user data...');
    const response = await fetchUserList();
    console.log('Received response:', response);
    
    // 修复：检查正确的响应格式
    if (response.data && response.data.code === 200 && response.data.data) {
      users.value = response.data.data;
      console.log('Loaded users:', users.value);
    } else {
      console.error('Invalid response format:', response);
      users.value = [];
    }
  } catch (error) {
    console.error('Error loading user data:', error);
    users.value = [];
    snackbarStore.showMessage('加载用户数据失败');
  } finally {
    loading.value = false;
  }
};

// 过滤功能
const filteredUsers = computed(() => {
  return users.value.filter(user => {
    if (filters.role && user.role !== filters.role) return false;
    if (filters.gender && user.gender !== filters.gender) return false;
    if (filters.is_active !== null && user.is_active !== filters.is_active) return false;
    return true;
  });
});

// 事件处理
const handleApplyFilter = () => {
  console.log('Applying filters:', filters);
};

const handleRefreshItem = () => {
  loadData();
};

const handleViewItem = (user: IPsychologicalUser) => {
  console.log('Viewing user:', user);
  const extraInfo = parseExtraInfo(user.extra_info);
  alert(`用户详情：\n姓名：${user.name}\n角色：${getRoleText(user.role)}\n额外信息：${JSON.stringify(extraInfo, null, 2)}`);
};

// 编辑用户
const handleEditItem = (user: IPsychologicalUser) => {
  editingUser.value = user;
  editForm.username = user.username;
  editForm.name = user.name;
  editForm.phone = user.phone;
  editForm.gender = user.gender;
  editForm.role = user.role;
  editForm.is_active = user.is_active;
  editDialog.value = true;
};

// 保存编辑
const handleSaveEdit = async () => {
  if (!editingUser.value) return;
  
  try {
    console.log('发送编辑请求:', editForm);
    const response = await updateUser(editingUser.value.id, editForm);
    console.log('编辑响应:', response);
    
    // 检查响应格式 - 同时检查success和code字段
    if (response.data && (response.data.success || response.data.code === 200)) {
      snackbarStore.showMessage('用户信息更新成功');
      editDialog.value = false;
      loadData(); // 重新加载数据
    } else {
      const errorMsg = response.data?.message || response.data?.data || '更新失败';
      snackbarStore.showMessage('更新失败：' + errorMsg);
    }
  } catch (error) {
    console.error('Update user error:', error);
    snackbarStore.showMessage('更新用户信息失败：网络错误');
  }
};

// 删除用户
const handleDeleteItem = (user: IPsychologicalUser) => {
  deletingUser.value = user;
  deleteDialog.value = true;
};

// 确认删除/恢复
const handleConfirmDelete = async () => {
  if (!deletingUser.value) return;
  
  const isDeleting = deletingUser.value.is_active;
  const operation = isDeleting ? '删除' : '恢复';
  
  try {
    console.log(`发送${operation}请求:`, deletingUser.value.id);
    
    if (isDeleting) {
      // 删除操作（软删除）
      const response = await deleteUser(deletingUser.value.id);
      console.log('删除响应:', response);
      
      if (response.data && (response.data.success || response.data.code === 200)) {
        snackbarStore.showMessage('用户删除成功');
        deleteDialog.value = false;
        loadData();
      } else {
        const errorMsg = response.data?.message || response.data?.data || '删除失败';
        snackbarStore.showMessage('删除失败：' + errorMsg);
      }
    } else {
      // 恢复操作（将 is_active 设为 true）
      const updateData = {
        username: deletingUser.value.username,
        name: deletingUser.value.name,
        phone: deletingUser.value.phone,
        gender: deletingUser.value.gender,
        role: deletingUser.value.role,
        is_active: true
      };
      
      const response = await updateUser(deletingUser.value.id, updateData);
      console.log('恢复响应:', response);
      
      if (response.data && (response.data.success || response.data.code === 200)) {
        snackbarStore.showMessage('用户恢复成功');
        deleteDialog.value = false;
        loadData();
      } else {
        const errorMsg = response.data?.message || response.data?.data || '恢复失败';
        snackbarStore.showMessage('恢复失败：' + errorMsg);
      }
    }
  } catch (error) {
    console.error(`${operation} user error:`, error);
    snackbarStore.showMessage(`${operation}用户失败：网络错误`);
  }
};

const handleClear = () => {
  filters.role = '';
  filters.gender = '';
  filters.is_active = null;
};

const handleResetFilter = () => {
  handleClear();
  loadData();
};

// 组件挂载时加载数据
onMounted(() => {
  loadData();
});
</script>

<template>
  <section>
    <VRow>
      <VCol cols="12">
        <VCard>
          <VCardItem class="py-0">
            <VToolbar tag="div" color="transparent" flat>
              <VToolbarTitle>心理咨询系统用户管理</VToolbarTitle>
              <VSpacer />
              <VBtn 
                :prepend-icon="!showFilter ? 'mdi-filter-variant-plus' : 'mdi-filter-variant'"
                @click="showFilter = !showFilter"
                density="comfortable"
                variant="outlined"
              >
                {{ showFilter ? '隐藏筛选' : '显示筛选' }}
              </VBtn>
              <VBtn icon @click="handleRefreshItem" density="comfortable">
                <VIcon>mdi-refresh</VIcon>
                <VTooltip activator="parent">刷新数据</VTooltip>
              </VBtn>
            </VToolbar>
          </VCardItem>
          
          <!-- 筛选区域 -->
          <VSheet color="#FBFBFB" v-show="showFilter">
            <VCardText>
              <VRow>
                <VCol cols="12" md="3">
                  <VSelect 
                    v-model="filters.role" 
                    :items="roleOptions" 
                    label="角色筛选"
                    clearable
                  />
                </VCol>
                <VCol cols="12" md="3">
                  <VSelect 
                    v-model="filters.gender" 
                    :items="genderOptions" 
                    label="性别筛选"
                    clearable
                  />
                </VCol>
                <VCol cols="12" md="3">
                  <VSelect 
                    v-model="filters.is_active" 
                    :items="statusOptions" 
                    label="状态筛选"
                    clearable
                  />
                </VCol>
              </VRow>
            </VCardText>
            <VCardActions>
              <VSpacer />
              <VBtn @click="handleResetFilter">重置</VBtn>
              <VBtn color="primary" variant="outlined" @click="handleApplyFilter">应用筛选</VBtn>
            </VCardActions>
          </VSheet>
          
          <!-- 数据表格 -->
          <VCardText class="pa-0 pb-5">
            <VDivider />
            <VDataTable
              :headers="headers"
              :items="filteredUsers"
              v-model:items-per-page="itemsPerPage"
              :loading="loading"
              hover
              class="elevation-1"
            >
              <!-- 角色列 -->
              <template #item.role="{ item }">
                <VChip :color="item.role === 'ADMIN' ? 'error' : item.role === 'CONSULTANT' ? 'primary' : 'default'" size="small">
                  {{ getRoleText(item.role) }}
                </VChip>
              </template>
              
              <!-- 性别列 -->
              <template #item.gender="{ item }">
                <VIcon :color="item.gender === 'M' ? 'blue' : 'pink'">
                  {{ item.gender === 'M' ? 'mdi-gender-male' : 'mdi-gender-female' }}
                </VIcon>
                {{ getGenderText(item.gender) }}
              </template>
              
              <!-- 状态列 -->
              <template #item.is_active="{ item }">
                <VChip :color="getStatusColor(item.is_active)" size="small">
                  {{ item.is_active ? '激活' : '禁用' }}
                </VChip>
              </template>
              
              <!-- 操作列 -->
              <template #item.action="{ item }">
                <div class="d-flex gap-2">
                  <VBtn 
                    size="small"
                    color="primary" 
                    variant="outlined"
                    prepend-icon="mdi-pencil"
                    @click="handleEditItem(item)"
                  >
                    编辑
                  </VBtn>
                  <VBtn 
                    size="small"
                    :color="item.is_active ? 'warning' : 'success'" 
                    variant="outlined"
                    :prepend-icon="item.is_active ? 'mdi-archive' : 'mdi-restore'"
                    @click="handleDeleteItem(item)"
                  >
                    {{ item.is_active ? '删除' : '恢复' }}
                  </VBtn>
                </div>
              </template>
            </VDataTable>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>
    
    <!-- 数据统计卡片 -->
    <VRow class="mt-4">
      <VCol cols="12" md="3">
        <VCard color="primary" variant="tonal">
          <VCardText>
            <div class="d-flex justify-space-between">
              <div>
                <h3>{{ users.filter(u => u.role === 'STUDENT').length }}</h3>
                <p>学生用户</p>
              </div>
              <VIcon size="40">mdi-school</VIcon>
            </div>
          </VCardText>
        </VCard>
      </VCol>
      <VCol cols="12" md="3">
        <VCard color="success" variant="tonal">
          <VCardText>
            <div class="d-flex justify-space-between">
              <div>
                <h3>{{ users.filter(u => u.role === 'CONSULTANT').length }}</h3>
                <p>咨询师</p>
              </div>
              <VIcon size="40">mdi-account-heart</VIcon>
            </div>
          </VCardText>
        </VCard>
      </VCol>
      <VCol cols="12" md="3">
        <VCard color="warning" variant="tonal">
          <VCardText>
            <div class="d-flex justify-space-between">
              <div>
                <h3>{{ users.filter(u => u.role === 'INITIAL_VISITOR').length }}</h3>
                <p>初访员</p>
              </div>
              <VIcon size="40">mdi-account-search</VIcon>
            </div>
          </VCardText>
        </VCard>
      </VCol>
      <VCol cols="12" md="3">
        <VCard color="info" variant="tonal">
          <VCardText>
            <div class="d-flex justify-space-between">
              <div>
                <h3>{{ users.filter(u => u.is_active).length }}</h3>
                <p>激活用户</p>
              </div>
              <VIcon size="40">mdi-account-check</VIcon>
            </div>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- 编辑对话框 -->
    <VDialog v-model="editDialog" max-width="600px" @keydown.esc="editDialog = false" @click:outside="editDialog = false">
      <VCard>
        <VCardTitle>编辑用户</VCardTitle>
        <VCardText>
          <VForm>
            <VRow>
              <VCol cols="12">
                <VTextField
                  label="用户名"
                  v-model="editForm.username"
                  :rules="[(v) => !!v || '用户名不能为空']"
                  required
                />
              </VCol>
              <VCol cols="12">
                <VTextField
                  label="姓名"
                  v-model="editForm.name"
                  :rules="[(v) => !!v || '姓名不能为空']"
                  required
                />
              </VCol>
              <VCol cols="12">
                <VTextField
                  label="电话"
                  v-model="editForm.phone"
                  :rules="[(v) => !!v || '电话不能为空']"
                  required
                />
              </VCol>
              <VCol cols="12" md="6">
                <VSelect
                  label="性别"
                  v-model="editForm.gender"
                  :items="genderOptions"
                  :rules="[(v) => !!v || '性别不能为空']"
                  required
                />
              </VCol>
              <VCol cols="12" md="6">
                <VSelect
                  label="角色"
                  v-model="editForm.role"
                  :items="roleOptions"
                  :rules="[(v) => !!v || '角色不能为空']"
                  required
                />
              </VCol>
              <VCol cols="12">
                <VSwitch
                  label="状态"
                  v-model="editForm.is_active"
                />
              </VCol>
            </VRow>
          </VForm>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn color="primary" variant="outlined" @click="handleSaveEdit">保存</VBtn>
          <VBtn color="error" variant="outlined" @click="editDialog = false">取消</VBtn>
        </VCardActions>
      </VCard>
    </VDialog>

    <!-- 删除/恢复确认对话框 -->
    <VDialog v-model="deleteDialog" max-width="400px" @keydown.esc="deleteDialog = false" @click:outside="deleteDialog = false">
      <VCard>
        <VCardTitle>{{ deletingUser?.is_active ? '确认删除' : '确认恢复' }}</VCardTitle>
        <VCardText>
          <template v-if="deletingUser?.is_active">
            您确定要删除用户 "{{ deletingUser?.username }}" 吗？
            <br/>
            <VAlert type="info" class="mt-2">
              <strong>注意：</strong>这是软删除，用户数据将被保留，但用户状态将变为"已删除"。
            </VAlert>
          </template>
          <template v-else>
            您确定要恢复用户 "{{ deletingUser?.username }}" 吗？
            <br/>
            <VAlert type="success" class="mt-2">
              <strong>说明：</strong>用户将重新激活，可以正常使用系统。
            </VAlert>
          </template>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn 
            :color="deletingUser?.is_active ? 'warning' : 'success'" 
            variant="outlined" 
            @click="handleConfirmDelete"
          >
            {{ deletingUser?.is_active ? '删除' : '恢复' }}
          </VBtn>
          <VBtn color="primary" variant="outlined" @click="deleteDialog = false">取消</VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </section>
</template>

<style scoped>
.elevation-1 {
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style> 